//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package net.mingsoft.basic.action;

import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.io.file.FileWriter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.mingsoft.base.entity.ResultData;
import net.mingsoft.basic.annotation.LogAnn;
import net.mingsoft.basic.biz.IAppBiz;
import net.mingsoft.basic.constant.e.BusinessTypeEnum;
import net.mingsoft.basic.constant.e.CookieConstEnum;
import net.mingsoft.basic.util.BasicUtil;
import net.mingsoft.config.MSProperties;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

@Api(
        tags = {"后端-基础接口"}
)
@Controller("/basicTemplate")
@RequestMapping({"/${ms.manager.path}/basic/template"})
public class TemplateAction extends BaseAction {
    @Autowired
    private IAppBiz appBiz;

    public TemplateAction() {
    }

    @ApiIgnore
    @GetMapping({"/index"})
    @RequiresPermissions({"basic:template:view"})
    public String index(HttpServletResponse response, HttpServletRequest request) {
        return "/WEB-INF/manager/basic/template/index";
    }

    @ApiIgnore
    @GetMapping({"/form"})
    @RequiresPermissions({"basic:template:view"})
    public String form(HttpServletResponse response, HttpServletRequest request) {
        return "/WEB-INF/manager/basic/template/form";
    }

    @ApiIgnore
    @GetMapping({"/edit"})
    @RequiresPermissions({"basic:template:view"})
    public String edit(HttpServletResponse response, HttpServletRequest request) {
        return "/WEB-INF/manager/basic/template/edit";
    }

    @ApiOperation("点击模板管理，获取所有的模板文件名")
    @ApiImplicitParam(
            name = "pageNo",
            value = "pageNo",
            required = true,
            paramType = "query"
    )
    @GetMapping({"/queryTemplateSkin"})
    @RequiresPermissions({"basic:template:view"})
    @ResponseBody
    protected ResultData queryTemplateSkin(HttpServletResponse response, HttpServletRequest request) {
        String pageNo = request.getParameter("pageNo");
        if (!NumberUtils.isNumber(pageNo)) {
            pageNo = "1";
        }

        List<String> folderNameList = this.queryTemplateFile();
        Map<String, Object> map = new HashMap(3);
        map.put("folderNameList", folderNameList);
        map.put("websiteId", BasicUtil.getApp().getAppId());
        map.put("pageNo", pageNo);
        BasicUtil.setCookie(response, CookieConstEnum.PAGENO_COOKIE, pageNo);
        return ResultData.build().success(map);
    }

    @ApiOperation("写入模板文件内容")
    @ApiImplicitParams({@ApiImplicitParam(
            name = "fileName",
            value = "文件名称",
            required = true,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "fileContent",
            value = "文件内容",
            required = true,
            paramType = "query"
    )})
    @LogAnn(
            title = "写入模板文件内容",
            businessType = BusinessTypeEnum.UPDATE
    )
    @PostMapping({"/writeFileContent"})
    @ResponseBody
    public ResultData writeFileContent(@ApiIgnore ModelMap model, HttpServletRequest request, HttpServletResponse response) throws IOException {
        this.LOG.debug("ready modify template");
        String fileName = BasicUtil.getString("fileName");
        String uploadTemplatePath = MSProperties.upload.template;
        if (!StringUtils.isEmpty(fileName) && fileName.startsWith(uploadTemplatePath)) {
            String templets = BasicUtil.getRealTemplatePath(fileName);
            if (!FileUtil.exist(templets)) {
                return ResultData.build().error(this.getResString("failed.to.edit.a.template"));
            } else if (!this.checkFileType(fileName)) {
                return ResultData.build().error(this.getResString("failed.to.edit.a.template"));
            } else {
                String fileContent = BasicUtil.getString("fileContent");
                if (!StringUtils.isEmpty(fileName)) {
                    FileWriter.create(new File(templets)).write(fileContent);
                    this.LOG.debug("edit template file：{} success!", fileName);
                    return ResultData.build().success();
                } else {
                    return ResultData.build().error();
                }
            }
        } else {
            return ResultData.build().error(this.getResString("err.error", new String[]{this.getResString("file.name")}));
        }
    }

    @ApiOperation("删除模版")
    @ApiImplicitParam(
            name = "fileName",
            value = "模版名称",
            required = true,
            paramType = "query"
    )
    @LogAnn(
            title = "删除模版",
            businessType = BusinessTypeEnum.DELETE
    )
    @PostMapping({"/delete"})
    @ResponseBody
    @RequiresPermissions({"basic:template:del"})
    public ResultData delete(HttpServletRequest request) {
        String uploadTemplatePath = MSProperties.upload.template;
        String fileName = request.getParameter("fileName");
        if (fileName != null && (fileName.contains("..") || fileName.contains("../") || fileName.contains("..\\"))) {
            return ResultData.build().error("非法路径");
        } else {
            String path = BasicUtil.getRealTemplatePath(uploadTemplatePath + File.separator + BasicUtil.getApp().getAppId() + File.separator + fileName);

            try {
                FileUtils.deleteDirectory(new File(path));
                return ResultData.build().success();
            } catch (Exception var6) {
                return ResultData.build().error();
            }
        }
    }

    @ApiOperation("显示子文件和子文件夹")
    @ApiImplicitParam(
            name = "skinFolderName",
            value = "skinFolderName",
            required = true,
            paramType = "query"
    )
    @GetMapping({"/showChildFileAndFolder"})
    @ResponseBody
    public ResultData showChildFileAndFolder(HttpServletResponse response, HttpServletRequest request) {
        String uploadTemplatePath = MSProperties.upload.template;
        List<String> folderNameList = null;
        String skinFolderName = request.getParameter("skinFolderName");
        String filter = BasicUtil.getRealTemplatePath(uploadTemplatePath + File.separator + BasicUtil.getApp().getAppId());
        this.LOG.debug("过滤路径" + filter);
        if (skinFolderName == null || !skinFolderName.contains("../") && !skinFolderName.contains("..\\")) {
            String uploadFileUrl = uploadTemplatePath + File.separator + skinFolderName;
            File[] files = (new File(BasicUtil.getRealTemplatePath(uploadFileUrl))).listFiles();
            Map<String, Object> map = new HashMap();
            if (files != null) {
                folderNameList = new ArrayList();
                List<String> fileNameList = new ArrayList();

                for(int i = 0; i < files.length; ++i) {
                    File currFile = files[i];
                    String temp = currFile.getPath();
                    temp = temp.replace(File.separator.equals("\\") ? "/" : "\\", File.separator).replace(filter, "");
                    if (currFile.isDirectory()) {
                        folderNameList.add(temp);
                    } else {
                        fileNameList.add(temp);
                    }
                }

                map.put("folderNum", folderNameList.size());
                folderNameList.addAll(fileNameList);
                map.put("fileNameList", folderNameList);
            }

            map.put("uploadFileUrl", uploadFileUrl);
            map.put("websiteId", BasicUtil.getApp().getAppId());
            return ResultData.build().success(map);
        } else {
            return ResultData.build().error("非法路径");
        }
    }

    @ApiOperation("读取模版文件内容")
    @ApiImplicitParam(
            name = "fileName",
            value = "文件名称",
            required = true,
            paramType = "query"
    )
    @GetMapping({"/readFileContent"})
    @ResponseBody
    @RequiresPermissions({"basic:template:update"})
    public ResultData readFileContent(@ApiIgnore ModelMap model, HttpServletRequest request) {
        String fileName = request.getParameter("fileName");
        String uploadTemplatePath = MSProperties.upload.template;
        if (fileName == null || !fileName.contains("../") && !fileName.contains("..\\")) {
            fileName = uploadTemplatePath + File.separator + fileName;
            Map<String, Object> map = new HashMap();
            if (!StringUtils.isEmpty(fileName)) {
                map.put("fileContent", FileReader.create(new File(BasicUtil.getRealTemplatePath(fileName))).readString());
            }

            map.put("name", (new File(BasicUtil.getRealTemplatePath(fileName))).getName());
            map.put("fileName", fileName);
            map.put("fileNamePrefix", fileName.substring(0, fileName.lastIndexOf(File.separator) + 1));
            return ResultData.build().success(map);
        } else {
            return ResultData.build().error("非法路径");
        }
    }

    @ApiOperation("删除模版文件")
    @ApiImplicitParam(
            name = "fileName",
            value = "文件名称",
            required = true,
            paramType = "query"
    )
    @LogAnn(
            title = "删除模版文件",
            businessType = BusinessTypeEnum.DELETE
    )
    @PostMapping({"/deleteTemplateFile"})
    @ResponseBody
    public ResultData deleteTemplateFile(HttpServletRequest request) {
        String uploadTemplatePath = MSProperties.upload.template;
        String fileName = request.getParameter("fileName");
        if (fileName == null || !fileName.contains("../") && !fileName.contains("..\\")) {
            fileName = uploadTemplatePath + File.separator + BasicUtil.getApp().getAppId() + File.separator + fileName;
            FileUtil.del(BasicUtil.getRealTemplatePath(fileName));
            return ResultData.build().success();
        } else {
            return ResultData.build().error("非法路径");
        }
    }

    private void files(List list, File fileDir, String style) {
        if (fileDir.isDirectory()) {
            File[] files = fileDir.listFiles();

            for(int i = 0; i < files.length; ++i) {
                File currFile = files[i];
                if (currFile.isFile()) {
                    String ex = currFile.getName();
                    if (ex.endsWith("htm") || ex.endsWith("html")) {
                        String _pathName = new String();
                        _pathName = this.files(currFile, style, _pathName);
                        list.add(_pathName + currFile.getName());
                    }
                } else if (currFile.isDirectory()) {
                    this.files(list, currFile, style);
                }
            }
        }

    }

    private String files(File file, String style, String pathName) {
        if (!file.getParentFile().getName().equals(style)) {
            pathName = file.getParentFile().getName() + "/" + pathName;
            pathName = this.files(file.getParentFile(), style, pathName);
        }

        return pathName;
    }

    private List<String> queryTemplateFile() {
        String uploadTemplatePath = MSProperties.upload.template;
        List<String> folderNameList = null;
        String _path = uploadTemplatePath + File.separator + BasicUtil.getApp().getAppId() + File.separator;
        this.LOG.debug("当前站点：{}", BasicUtil.getApp().getAppName());
        this.LOG.debug("当前站点模板路径_path：{}", _path);
        String templates = BasicUtil.getRealTemplatePath(_path);
        this.LOG.debug("当前站点模板路径：{}", templates);
        File file = new File(templates);
        this.LOG.debug("是否存在：{}", file.exists());
        String[] str = file.list();
        if (str != null) {
            folderNameList = new ArrayList();

            for(int i = 0; i < str.length; ++i) {
                if (str[i].indexOf(".") < 0) {
                    folderNameList.add(str[i]);
                }
            }
        }

        return folderNameList;
    }

    protected boolean checkFileType(String fileName) {
        String uploadFileDenied = MSProperties.upload.denied;
        String[] errorType = uploadFileDenied.split(",");
        String fileType = FileUtil.getSuffix(fileName);
        if (StringUtils.isBlank(fileType)) {
            return false;
        } else {
            String[] var5 = errorType;
            int var6 = errorType.length;

            for(int var7 = 0; var7 < var6; ++var7) {
                String type = var5[var7];
                if (fileType.equalsIgnoreCase(type)) {
                    this.LOG.info("文件类型被拒绝:{}", fileName);
                    return false;
                }
            }

            return true;
        }
    }

    @ApiOperation("查询模版风格供站点选择")
    @GetMapping({"/queryAppTemplateSkin"})
    @ResponseBody
    public ResultData queryAppTemplateSkin(HttpServletRequest request) {
        List<String> folderNameList = this.queryTemplateFile();
        Map map = new HashMap();
        if (folderNameList != null) {
            map.put("appTemplates", folderNameList);
        }

        return ResultData.build().success(map);
    }

    @ApiOperation("查询模版文件供栏目选择，可指定模板名称，不传查询应用设置中选择的模板")
    @GetMapping({"/queryTemplateFileForColumn"})
    @ApiImplicitParams({@ApiImplicitParam(
            name = "appStyle",
            value = "可选，可以指定template下的文件夹名称",
            required = false,
            paramType = "query"
    )})
    @ResponseBody
    public ResultData queryTemplateFileForColumn(HttpServletRequest request) {
        String uploadTemplatePath = MSProperties.upload.template;
        String appStyle = BasicUtil.getString("appStyle", BasicUtil.getApp().getAppStyle());
        if (StringUtils.isBlank(appStyle)) {
            return ResultData.build().error();
        } else {
            String path = BasicUtil.getRealTemplatePath(uploadTemplatePath + File.separator + BasicUtil.getApp().getAppId() + File.separator);
            List<File> list = FileUtil.loopFiles(path + appStyle, new FileFilter() {
                public boolean accept(File pathname) {
                    try {
                        return FileTypeUtil.getType(pathname).equalsIgnoreCase("html") || FileTypeUtil.getType(pathname).equalsIgnoreCase("htm");
                    } catch (Exception var3) {
                        return false;
                    }
                }
            });
            List<String> collect = (List)list.stream().map((file) -> {
                return file.getPath().replaceAll("\\\\", "/").replace(path.replaceAll("\\\\", "/"), "").substring(appStyle.length() + 1);
            }).collect(Collectors.toList());
            return ResultData.build().success(collect);
        }
    }
}
